package org.dragonnova.meetingserver.server.activity;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ztspeech.AZTClient;

import org.dragonnova.meetingserver.R;
import org.dragonnova.meetingserver.model.bean.VoiceInfo;
import org.dragonnova.meetingserver.server.application.TransBoxApplication;
import org.dragonnova.meetingserver.server.adapter.ChatListAdapter;
import org.dragonnova.meetingserver.server.service.TranslationService;
import org.dragonnova.meetingserver.server.service.WIFIServiceTest;
import org.dragonnova.meetingserver.utils.Constants;
import org.dragonnova.meetingserver.utils.ContentResolverUtil;
import org.dragonnova.meetingserver.utils.LogUtil;
import org.dragonnova.meetingserver.utils.MyUtil;
import org.dragonnova.meetingserver.utils.PromptUtil;
import org.dragonnova.meetingserver.utils.UIHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends Activity implements OnClickListener, ServiceConnection {

    private static final String TAG = MainActivity.class.getName();
    private ImageView recCHButton;// 点击说中文的按钮
    private ImageView recENButton;// 点击说英文的按钮
    private TextView tv_rec_ch;// 点击录音的tv_中文
    private TextView tv_rec_en;// 点击录音的tv_英文
    private ImageView iv_arrow;//点击向上弹出的按钮
    private LinearLayout rl_btns_rec;//录音按钮的布局
    public ListView listView;// 存放聊天记录的listView
    private ChatListAdapter mAdapter;//聊天记录的适配器
    private TextView remindText;//显示临时的翻译内容

    private boolean isCH2EN = false;// 中英文输入的标志位
    private long exitTime = 0;// 保存点击返回的事件
    private ArrayList<VoiceInfo> chatList = new ArrayList<>();//存放聊天记录的list
    private boolean isBtnsShown = true;//点击按钮是否显示标记位
    private int mViewHeight;//按钮所在控件的高度
    private int mViewWidth;//按钮所在控件的宽度

    private WIFIServiceTest wifiService;//wifi服务
    private TranslationService.MyBinder transBinder;
    private TranslationService transService;

    private Dialog recoDialog;
    private Dialog noVoiceDialog;
    private Dialog noNetDialog;

    //=====================删除聊天记录的成员变量====================
    private ProgressBar progressBar;
    private TextView progressText;
    private ContentResolverUtil resolverUtil;
    private MyAsyncTask myAsyncTask;
    private boolean deleteCancel;
    private Dialog cleanDialog;
    private Dialog progressDialog;
    private ArrayList<VoiceInfo> chatHistory;
    //===============================================================

    /**
     * 处理事件的handler
     */
    @SuppressLint("HandlerLeak")
    private Handler mainHandler = new Handler() {

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        //=====================应用不被杀死的代码========================
       /* LogUtil.eee("activity start");
        //保持屏幕一直亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //判断service是否已经启动
        boolean serviceStatus = PackageUtil.getServiceStatus(this, "org.dragonnova.wifihsserver.server.service.RestartService");
        if (!serviceStatus) {
            Intent sIntent = new Intent(this, RestartService.class);
            this.startService(sIntent);
        }*/
        //===============================================================

        PromptUtil.poolPlay(getApplicationContext(), R.raw.application_started);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //=====================应用不被杀死的代码========================
        TransBoxApplication.getInstance().activityResumed(TransBoxApplication.MAINACTIVITY_STATUS);
        //===============================================================
    }

    @Override
    protected void onStart() {
        super.onStart();
        //设置点击view的时候出现提示音
        MyUtil.keytoneSetting(this, 1);

        //=====================应用不被杀死的代码========================
        //保持屏幕一直亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //去掉锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        //===============================================================

        //注册监听网络状态的广播
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(ConnectivityReceiver, mFilter);
        //初始化语音设置
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.APP_GLOBAL_CONFIG, MODE_PRIVATE);
        String tone = sharedPreferences.getString(Constants.KEY_SETTING_TONE, null);
        float voicespeed = sharedPreferences.getFloat(Constants.KEY_SETTING_VOICESPEED, -1L);
        if (mAdapter != null) showHistory();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isBtnsShown) {
            hideWithoutAnimation();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        resetStatus();
        //=====================应用不被杀死的代码========================
        TransBoxApplication.getInstance().activityPaused(TransBoxApplication.MAINACTIVITY_STATUS);
        //===============================================================

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService();
        unRegisterBroadcastReceiver();
        PromptUtil.dismissSoundPool();
        PromptUtil.dismissMediaPlayer();
    }

    /**
     * 当屏幕旋转时进行的处理
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof WIFIServiceTest.ServiceBinder) {
            wifiService = ((WIFIServiceTest.ServiceBinder) service).getService();
        } else if (service instanceof TranslationService.MyBinder) {
            transBinder = (TranslationService.MyBinder) service;
            transService = ((TranslationService.MyBinder) service).getService();
            //初始化聊天记录
            mAdapter = new ChatListAdapter(MainActivity.this, chatList, transBinder);
            listView.setAdapter(mAdapter);
            showHistory();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(TAG, "onServiceDisconnected");
        /*btService.onDestroy();
        wifiService.onDestroy();
        transService.onDestroy();*/
    }

    /**
     * 初始化
     */
    private void init() {
        initActionBar();
        recCHButton = (ImageView) this.findViewById(R.id.btn_rec_ch);
        recENButton = (ImageView) this.findViewById(R.id.btn_rec_en);
        tv_rec_en = (TextView) this.findViewById(R.id.tv_rec_en);
        tv_rec_ch = (TextView) this.findViewById(R.id.tv_rec_ch);
        iv_arrow = (ImageView) findViewById(R.id.iv_arrow);
        rl_btns_rec = (LinearLayout) findViewById(R.id.rl_btns_rec);
        listView = (ListView) this.findViewById(R.id.lv_chat);
        recCHButton.setOnClickListener(this);
        recENButton.setOnClickListener(this);
        iv_arrow.setOnClickListener(this);
        //设置滚动监听，让录音按钮消失
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                switch (i) {
                    case SCROLL_STATE_FLING:
                        if (isBtnsShown) {
                            rl_btns_rec.setPaddingRelative(0, (int) (-0.5 * mViewHeight), 0, (int) (-0.5 * mViewHeight));
                            iv_arrow.setRotation(0);
                            isBtnsShown = false;
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        //检查网路状况
        if (!MyUtil.isNetworkAvailable(this)) {
            Toast.makeText(this, getText(R.string.err_no_connection), Toast.LENGTH_SHORT).show();
        }
        //设置网络连接的服务器
        setWebServerInfo();
        //测量按钮控件的高度，然后使控件隐藏
        ViewTreeObserver vto = rl_btns_rec.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                mViewHeight = rl_btns_rec.getMeasuredHeight();
                mViewWidth = rl_btns_rec.getMeasuredWidth();
                rl_btns_rec.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                hideWithoutAnimation();
            }
        });
        //绑定服务
        bindService();
        registerBroadcastReceiver();
    }

    /**
     * 初始化actionbar
     */
    private void initActionBar() {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setCustomView(R.layout.actionbar);
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            TextView textView = (TextView) actionBar.getCustomView()
                    .findViewById(R.id.tv_act_bar);
            textView.setText(getString(R.string.actionbar_main));
            Button btnLeft = (Button) actionBar.getCustomView().findViewById(
                    R.id.btn_left_act_bar);
            btnLeft.setVisibility(View.INVISIBLE);
            Button btnRight = (Button) actionBar.getCustomView().findViewById(
                    R.id.btn_right_act_bar);
            Button btnRight2 = (Button) actionBar.getCustomView().findViewById(
                    R.id.btn_right2_act_bar);
            btnRight2.setVisibility(View.VISIBLE);
            btnRight.setBackgroundResource(R.drawable.actionbar_main_right);
            btnRight2.setBackgroundResource(R.drawable.actionbar_main_right2);
            btnRight.setOnClickListener(this);
            btnRight2.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_right_act_bar:
                showCleanDialog();
                break;
            case R.id.btn_right2_act_bar:
                break;
            case R.id.btn_rec_ch:
                stopAll();
                isCH2EN = true;
                setButtonEnable(false);
                recordAndShow();
                break;
            case R.id.btn_rec_en:
                stopAll();
                isCH2EN = false;
                setButtonEnable(false);
                recordAndShow();
                break;
            case R.id.iv_arrow:
                if (isBtnsShown) {
                    hideAnimation();
                } else {
                    showAnimation();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 显示录音按钮动画
     */
    private void showAnimation() {
        ObjectAnimator oa4 = ObjectAnimator.ofFloat(iv_arrow, "rotation", 0,
                180);
        oa4.setDuration(100);
        oa4.start();
        isBtnsShown = true;
        mHeight = -mViewHeight;
        timeHandler.sendEmptyMessage(0);
        tv_rec_ch.setText(getString(R.string.tv_rec_ch));
        tv_rec_en.setText(getString(R.string.tv_rec_en));
    }

    /**
     * 隐藏录音按钮动画
     */
    private void hideAnimation() {
        ObjectAnimator oa2 = ObjectAnimator.ofFloat(iv_arrow, "rotation", 180,
                360);
        oa2.setDuration(100);
        oa2.start();
        isBtnsShown = false;
        mHeight = 0;
        currentPosition = listView.getLastVisiblePosition();
        timeHandler.sendEmptyMessage(0);
        tv_rec_ch.setText(getString(R.string.tv_rec_ch_headset));
        tv_rec_en.setText(getString(R.string.tv_rec_en_headset));

    }

    /**
     * 隐藏录音按钮,没有动画
     */
    private void hideWithoutAnimation() {
        isBtnsShown = false;
        iv_arrow.setRotation(0);
        rl_btns_rec.setPaddingRelative(0, (int) (-0.5 * mViewHeight), 0, (int) (-0.5 * mViewHeight));
        tv_rec_ch.setText(getString(R.string.tv_rec_ch_headset));
        tv_rec_en.setText(getString(R.string.tv_rec_en_headset));
    }

    /**
     * 用handler模拟动画
     */
    private int mHeight;
    private TimeHandler timeHandler = new TimeHandler();
    private int currentPosition;

    @SuppressLint("HandlerLeak")
    private class TimeHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                rl_btns_rec.setPaddingRelative(0, (int) (0.5 * mHeight), 0, (int) (0.5 * mHeight));
                this.sendEmptyMessage(1);
            } else {
                //listView.setSelection(mAdapter.getCount() - 1);
                doAnimation();
            }
        }
    }

    /**
     * 做动画
     */
    private void doAnimation() {
        if (!isBtnsShown) {
            if (mHeight > -mViewHeight) {
                mHeight = mHeight - 50;
                timeHandler.sendEmptyMessage(0);
            }
        } else {
            if (mHeight < 0) {
                mHeight = mHeight + 50;
                timeHandler.sendEmptyMessage(0);
            }
        }
    }

    /**
     *
     */
    private void bindService() {
        //启动服务
        /*Intent wifiIntent = new Intent(MainActivity.this, BTService.class);
        bindService(wifiIntent, this, BIND_AUTO_CREATE);*/
        Intent btIntent = new Intent(MainActivity.this, WIFIServiceTest.class);
        bindService(btIntent, this, BIND_AUTO_CREATE);
        //启动翻译服务
        Intent intent = new Intent(this, TranslationService.class);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    /**
     * 解除服务绑定
     */
    private void unbindService() {
        unbindService(this);
        LogUtil.eee("unbind service successfully");
    }

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.TRANS_BORADCAST_ACTION);
        registerReceiver(TranslationReceiver, filter);
    }

    private void unRegisterBroadcastReceiver() {
        unregisterReceiver(TranslationReceiver);
    }

    /**
     * 检查网络情况
     */
    private void checkNetwork(Context context) {
        Intent intent;
        if (android.os.Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        } else {
            intent = new Intent();
            ComponentName componentName = new ComponentName(
                    "com.android.settings",
                    "com.android.setting.WirelessSettings");
            intent.setComponent(componentName);
            intent.setAction("android.intent.action.VIEW");
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 语音输入的提示框
     */
    @SuppressLint("InflateParams")
    private void showRecoDialog() {
        if (recoDialog == null) {
            recoDialog = UIHelper.getCircularCornerDialog(this);
            Button negButton = (Button) recoDialog.findViewById(R.id.dialog_btn_neg);
            Button posButton = (Button) recoDialog.findViewById(R.id.dialog_btn_pos);
            remindText = (TextView) recoDialog.findViewById(R.id.dialog_remind);
            negButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //语音识别取消
                    if (recoDialog.isShowing()) {
                        recoDialog.cancel();
                    }
                    setButtonEnable(true);
                    stopRecordNoRecognize();
                }
            });
            posButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //语音识别完成
                    if (recoDialog.isShowing()) {
                        recoDialog.cancel();
                    }
                    setButtonEnable(true);
                    stopRecord();
                }
            });
            recoDialog.setCanceledOnTouchOutside(false);
            recoDialog.setCancelable(false);
        }
        if (isCH2EN) {
            recoDialog = UIHelper.setCircularCornerDialogContent(recoDialog, R.drawable.icon_voice, getString(R.string.dialog_rec_remind_ch), getString(R.string.dialog_rec_finish_ch), getString(R.string.dialog_rec_cancel_ch));
        } else {
            recoDialog = UIHelper.setCircularCornerDialogContent(recoDialog, R.drawable.icon_voice, getString(R.string.dialog_rec_remind_en), getString(R.string.dialog_rec_finish_en), getString(R.string.dialog_rec_cancel_en));
        }
        recoDialog.show();
    }

    /**
     * 没有声音的提示框
     */
    @SuppressLint("InflateParams")
    private void showNoVoiceDialog() {
        if (noVoiceDialog == null) {
            noVoiceDialog = UIHelper.getCircularCornerDialog(this);
            Button negButton = (Button) noVoiceDialog.findViewById(R.id.dialog_btn_neg);
            Button posButton = (Button) noVoiceDialog.findViewById(R.id.dialog_btn_pos);
            negButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (noVoiceDialog.isShowing()) {
                        noVoiceDialog.cancel();
                    }
                    setButtonEnable(true);
                }
            });
            posButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (noVoiceDialog.isShowing()) {
                        noVoiceDialog.cancel();
                    }
                    stopAll();
                    setButtonEnable(false);
                    recordAndShow();
                }
            });
            noVoiceDialog.setCanceledOnTouchOutside(false);
            noVoiceDialog.setCancelable(false);
        }
        if (isCH2EN) {
            noVoiceDialog = UIHelper.setCircularCornerDialogContent(noVoiceDialog, R.drawable.dialog_no_voice, getString(R.string.dialog_no_voice_msg_ch), getString(R.string.dialog_no_voice_retry_ch), getString(R.string.dialog_no_voice_cancel_ch));
        } else {
            noVoiceDialog = UIHelper.setCircularCornerDialogContent(noVoiceDialog, R.drawable.dialog_no_voice, getString(R.string.dialog_no_voice_msg_en), getString(R.string.dialog_no_voice_retry_en), getString(R.string.dialog_no_voice_cancel_en));
        }
        noVoiceDialog.show();
    }

    /**
     * 没有网络的提示框
     */
    @SuppressLint("InflateParams")
    private void showNoNetworkDialog() {
        if (noNetDialog == null) {
            noNetDialog = UIHelper.getCircularCornerDialog(this);
            Button negButton = (Button) noNetDialog.findViewById(R.id.dialog_btn_neg);
            Button posButton = (Button) noNetDialog.findViewById(R.id.dialog_btn_pos);
            negButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (noNetDialog.isShowing()) {
                        noNetDialog.cancel();
                    }
                    setButtonEnable(true);
                }
            });
            posButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (noNetDialog.isShowing()) {
                        noNetDialog.cancel();
                    }
                    setButtonEnable(true);
                    checkNetwork(getApplicationContext());
                }
            });
            noNetDialog.setCanceledOnTouchOutside(false);
            noNetDialog.setCancelable(false);
        }
        if (isCH2EN) {
            noNetDialog = UIHelper.setCircularCornerDialogContent(noNetDialog, R.drawable.dialog_no_network, getString(R.string.dialog_no_network_msg_ch), getString(R.string.dialog_no_network_set_ch), getString(R.string.dialog_no_network_cancel_ch));
        } else {
            noNetDialog = UIHelper.setCircularCornerDialogContent(noNetDialog, R.drawable.dialog_no_network, getString(R.string.dialog_no_network_msg_en), getString(R.string.dialog_no_network_set_en), getString(R.string.dialog_no_network_cancel_en));
        }
        noNetDialog.show();
    }

    /**
     * 显示聊天记录
     */
    private void showHistory() {
        chatList.clear();
        String userId = TransBoxApplication.getInstance().getCurrentUserName();
        if (TextUtils.isEmpty(userId)) userId = "null";
        ContentResolverUtil resolverUtil = new ContentResolverUtil(this);
        chatList.addAll(resolverUtil.findHistory(userId));
        Collections.reverse(chatList);
        mAdapter.notifyDataSetChanged();
        listView.setSelection(mAdapter.getCount() - 1);
    }

    /**
     * 翻译的服务器地址设置
     */
    private void setWebServerInfo() {
        String orgServerPath = getString(R.string.server_addr);
        String hzServerPath = getString(R.string.server_addr_hangzhou);
        String path = hzServerPath + ":" + getResources().getInteger(R.integer.server_port)
                + "/" + getString(R.string.servlet_path);
        AZTClient.setServerPath(path);
    }

    /**
     * 重置状态
     */
    private void resetStatus() {
        //取消点击view的提示音
        MyUtil.keytoneSetting(this, 0);
        //让屏幕不是一直亮
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //注销网络状态监听广播
        if (ConnectivityReceiver != null) {
            try {
                unregisterReceiver(ConnectivityReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //停止录音播放和识别
        stopAll();

        if (noVoiceDialog != null && noVoiceDialog.isShowing()) {
            noVoiceDialog.cancel();
        }
        if (recoDialog != null && recoDialog.isShowing()) {
            recoDialog.cancel();
        }
        if (noNetDialog != null && noNetDialog.isShowing()) {
            noNetDialog.cancel();
        }
        setButtonEnable(true);
    }

    /**
     * 开始录音并弹窗
     */
    private void recordAndShow() {
        showRecoDialog();
        startRecord();
    }

    /**
     * 开始录音
     */
    private void startRecord() {
        transBinder.startRecord(isCH2EN);
    }

    /**
     * 结束录音
     */
    private void stopRecord() {
        transBinder.stopRecord();
    }

    /**
     * 结束录音,且不保存，不识别
     */
    private void stopRecordNoRecognize() {
        transBinder.stopRecordNoRecognize();
    }

    /**
     * 停止录音,播放,停止合成及消息队列
     */
    private void stopAll() {
        if (transBinder != null) transBinder.stopAll();
    }

    /**
     * 监听网络状态的广播
     */
    private BroadcastReceiver ConnectivityReceiver = new BroadcastReceiver() {
        private ConnectivityManager broadcastReceiver;
        private NetworkInfo netInfo;

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                broadcastReceiver = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                netInfo = broadcastReceiver.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable() && netInfo.isConnected()) {

                    ///网络连接
                    String name = netInfo.getTypeName();

                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        LogUtil.eee("TYPE_WIFI");
                        //WiFi网络
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        LogUtil.eee("TYPE_ETHERNET");
                        //有线网络
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        LogUtil.eee("TYPE_MOBILE");
                        //3g网络
                    }
                    if (noNetDialog != null && noNetDialog.isShowing()) {
                        noNetDialog.cancel();
                    }
                } else {
                    showNoNetworkDialog();
                }
            }
        }
    };

    /**
     * 设置button是否可用
     */
    private void setButtonEnable(boolean isEnable) {
        recCHButton.setEnabled(isEnable);
        recENButton.setEnabled(isEnable);
    }

    /**
     * 设置button是否可用
     */
    private BroadcastReceiver TranslationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.TRANS_BORADCAST_ACTION.equals(intent.getAction())) {
                String action = intent.getStringExtra(Constants.BORADCAST_INTENT_OPTION);
                switch (action) {
                    case TranslationService.EXTRA_MEDIA_BUTTON_CLICK:
                        isCH2EN = intent.getBooleanExtra("isCH2EN", true);
                        setButtonEnable(false);
                        recordAndShow();
                        break;
                    case TranslationService.EXTRA_VAD_STOP:
                        if (recoDialog != null && recoDialog.isShowing()) {
                            recoDialog.cancel();
                        }
                        setButtonEnable(true);
                        break;
                    case TranslationService.EXTRA_TEMP_RESULT_CHANGED:
                        String tempResult = intent.getStringExtra("tempResult");
                        remindText.setText(tempResult);
                        break;
                    case TranslationService.EXTRA_TRANSLATED:
                        VoiceInfo voiceInfo = (VoiceInfo) intent.getSerializableExtra("voiceInfo");
                        chatList.add(voiceInfo);
                        mAdapter.notifyDataSetChanged();
                        listView.setSelection(mAdapter.getCount() - 1);
                        if (recoDialog != null && recoDialog.isShowing()) {
                            recoDialog.cancel();
                        }
                        setButtonEnable(true);
                        break;
                    case TranslationService.EXTRA_NO_RESULT:
                        if (recoDialog != null && recoDialog.isShowing()) {
                            recoDialog.cancel();
                        }
                        showNoVoiceDialog();
                        break;
                }
            }
        }
    };

    public void toCleanHistory(View view) {
        if (TransBoxApplication.getInstance().getCurrentIsLogin()) {
            showCleanDialog();
        } else {
            Toast.makeText(this, "未登录用户无法进行此操作，请先登录",
                    Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 清除聊天记录的提示框
     */
    private void showCleanDialog() {
        if (cleanDialog == null) {
            cleanDialog = UIHelper.getCircularNoImageDialog(this);
            Button posButton = (Button) cleanDialog.findViewById(R.id.dialog_btn_pos);
            Button negButton = (Button) cleanDialog.findViewById(R.id.dialog_btn_neg);
            posButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (cleanDialog.isShowing()) {
                        resolverUtil = new ContentResolverUtil(MainActivity.this);
                        chatHistory = resolverUtil.findHistory(TransBoxApplication.getInstance().getCurrentUserName());
                        Collections.reverse(chatHistory);
                        deleteCancel = false;
                        showProgressDialog();
                        myAsyncTask = new MyAsyncTask();
                        myAsyncTask.execute();
                        cleanDialog.cancel();
                    }
                }
            });
            negButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (cleanDialog.isShowing()) {
                        cleanDialog.cancel();
                    }
                }
            });
        }
        cleanDialog = UIHelper.setCircularNoImageDialogContent(cleanDialog, getString(R.string.dialog_clean), getString(R.string.dialog_clean_yes), getString(R.string.dialog_clean_no));
        cleanDialog.show();
    }

    /**
     * 进度条的提示框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = UIHelper.getCircularProgressDialog(this);
            Button posButton = (Button) progressDialog.findViewById(R.id.dialog_btn_pos);
            Button negButton = (Button) progressDialog.findViewById(R.id.dialog_btn_neg);
            progressBar = (ProgressBar) progressDialog.findViewById(R.id.dialog_progress);
            progressText = (TextView) progressDialog.findViewById(R.id.dialog_remind);
            posButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (progressDialog.isShowing()) {
                        progressDialog.cancel();
                    }
                }
            });
            negButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (progressDialog.isShowing()) {
                        deleteCancel = true;
                    }
                }
            });
        }
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog = UIHelper.setCircularProgressDialogContent(progressDialog, getString(R.string.dialog_progress), getString(R.string.dialog_progress_yes), getString(R.string.dialog_progress_no));
        progressDialog.show();
    }

    /**
     * 异步任务
     */
    private class MyAsyncTask extends AsyncTask<String, Integer, String> {

        /**
         * 运行到主线程 主要做一些初始化的工作
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setMax(chatHistory.size());
            String text = "删除完成:" + chatHistory.size() + "/" + chatHistory.size();
            progressText.setText(text);
        }

        /**
         * 运行到子线程
         */
        @Override
        protected String doInBackground(String... params) {
            File voiceFile;
            int count = 0;
            boolean deleteResult = false;
            for (int i = 0; i < chatHistory.size(); i++) {
                if (deleteCancel) break;
                SystemClock.sleep(500);
                int databaseResult = resolverUtil.deleteChatHistoryById(chatHistory.get(i).getUserId(), chatHistory.get(i).getId());
                if (databaseResult > 0) {
                    voiceFile = new File(chatHistory.get(i).getOrgPath());
                    if (voiceFile.exists()) deleteResult = voiceFile.delete();
                    if (deleteResult) count++;
                    publishProgress(count);
                }
            }
            return "删除完成:" + count + "/" + chatHistory.size();
        }

        /**
         * 更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
            String text = "删除进度：" + values[0] + "/" + chatHistory.size();
            progressText.setText(text);
        }

        /**
         * 运行到主线程
         */
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressText.setText(result);
        }
    }
}
